﻿/// <reference name="MicrosoftAjax.js"/>

(function() {

    function execute() {
        Type._registerScript("BatikScriptDataSource.js", ["MicrosoftAjaxComponentModel.js"]);

        Type.registerNamespace("Batik.Data");

        Batik.Data.ScriptDataSource = function() {
            Batik.Data.ScriptDataSource.initializeBase(this);
            this._data = null;
            this._events = null;
            this._objectTypeName = null;
            this._selectMethod = null;
            this._deleteMethod = null;
            this._updateMethod = null;
        }

        Batik.Data.ScriptDataSource.prototype = {
            initialize: function() {
                Batik.Data.ScriptDataSource.callBaseMethod(this, 'initialize');
                // Add custom initialization here
            },
            dispose: function() {
                //Add custom dispose actions here
                Batik.Data.ScriptDataSource.callBaseMethod(this, 'dispose');
            },
            set_data: function(value) {
                this._data = value;
            },
            get_data: function() {
                return this._data || null;
            },
            set_objectTypeName: function(value) {
                var e = Function._validateParams(arguments, [
                        { name: "value", type: String }
                    ]);
                if (e) throw e;
                this._objectTypeName = value;
            },
            get_objectTypeName: function() {
                return this._objectTypeName || null;
            },
            set_selectMethod: function(value) {
                var e = Function._validateParams(arguments, [
                        { name: "value", type: String }
                    ]);
                if (e) throw e;
                this._selectMethod = value;
            },
            get_selectMethod: function() {
                return this._selectMethod || null;
            },
            set_deleteMethod: function(value) {
                var e = Function._validateParams(arguments, [
                        { name: "value", type: String }
                    ]);
                if (e) throw e;
                this._deleteMethod = value;
            },
            get_deleteMethod: function() {
                return this._deleteMethod || null;
            },
            set_updateMethod: function(value) {
                var e = Function._validateParams(arguments, [
                        { name: "value", type: String }
                    ]);
                if (e) throw e;
                this._updateMethod = value;
            },
            get_updateMethod: function() {
                return this._updateMethod || null;
            },
            set_insertMethod: function(value) {
                var e = Function._validateParams(arguments, [
                        { name: "value", type: String }
                    ]);
                if (e) throw e;
                this._insertMethod = value;
            },
            get_insertMethod: function() {
                return this._insertMethod || null;
            },
            get_events: function() {
                if (!this._events) {
                    this._events = new Sys.EventHandlerList();
                }
                return this._events;
            },
            add_selectCompleted: function(handler) {
                var e = Function._validateParams(arguments, [
                    { name: "handler", type: Function }
                ]);
                // Add handler to list.
                this.get_events().addHandler('selectCompleted', handler);
            },
            remove_selectCompleted: function(handler) {
                var e = Function._validateParams(arguments, [
                    { name: "handler", type: Function }
                ]);
                // Remove handler from list.
                this.get_events().removeHandler('selectCompleted', handler);
            },
            add_selectError: function(handler) {
                var e = Function._validateParams(arguments, [
                        { name: "handler", type: Function }
                    ]);
                // Add handler to list.
                this.get_events().addHandler('selectError', handler);
            },
            remove_selectError: function(handler) {
                var e = Function._validateParams(arguments, [
                    { name: "handler", type: Function }
                ]);
                // Remove handler from list.
                this.get_events().removeHandler('selectError', handler);
            },
            add_deleteCompleted: function(handler) {
                var e = Function._validateParams(arguments, [
                    { name: "handler", type: Function }
                ]);
                // Add handler to list.
                this.get_events().addHandler('deleteCompleted', handler);
            },
            remove_deleteCompleted: function(handler) {
                var e = Function._validateParams(arguments, [
                    { name: "handler", type: Function }
                ]);
                // Remove handler from list.
                this.get_events().removeHandler('deleteCompleted', handler);
            },
            add_deleteError: function(handler) {
                var e = Function._validateParams(arguments, [
                        { name: "handler", type: Function }
                    ]);
                // Add handler to list.
                this.get_events().addHandler('deleteError', handler);
            },
            remove_deletetError: function(handler) {
                var e = Function._validateParams(arguments, [
                    { name: "handler", type: Function }
                ]);
                // Remove handler from list.
                this.get_events().removeHandler('deleteError', handler);
            },
            add_updateCompleted: function(handler) {
                var e = Function._validateParams(arguments, [
                    { name: "handler", type: Function }
                ]);
                // Add handler to list.
                this.get_events().addHandler('updateCompleted', handler);
            },
            remove_updateCompleted: function(handler) {
                var e = Function._validateParams(arguments, [
                    { name: "handler", type: Function }
                ]);
                // Remove handler from list.
                this.get_events().removeHandler('updateCompleted', handler);
            },
            add_updateError: function(handler) {
                var e = Function._validateParams(arguments, [
                        { name: "handler", type: Function }
                    ]);
                // Add handler to list.
                this.get_events().addHandler('updateError', handler);
            },
            remove_updateError: function(handler) {
                var e = Function._validateParams(arguments, [
                    { name: "handler", type: Function }
                ]);
                // Remove handler from list.
                this.get_events().removeHandler('updateError', handler);
            },
            add_insertCompleted: function(handler) {
                var e = Function._validateParams(arguments, [
                    { name: "handler", type: Function }
                ]);
                // Add handler to list.
                this.get_events().addHandler('insertCompleted', handler);
            },
            remove_insertCompleted: function(handler) {
                var e = Function._validateParams(arguments, [
                    { name: "handler", type: Function }
                ]);
                // Remove handler from list.
                this.get_events().removeHandler('insertCompleted', handler);
            },
            add_insertError: function(handler) {
                var e = Function._validateParams(arguments, [
                        { name: "handler", type: Function }
                    ]);
                // Add handler to list.
                this.get_events().addHandler('insertError', handler);
            },
            remove_insertError: function(handler) {
                var e = Function._validateParams(arguments, [
                    { name: "handler", type: Function }
                ]);
                // Remove handler from list.
                this.get_events().removeHandler('insertError', handler);
            },
            _raiseEvent: function(eventName, eventArgs) {
                var e = Function._validateParams(arguments, [
                    { name: "eventName", type: String },
                    { name: "eventArgs", type: Sys.EventArgs, mayBeNull: true, optional: true }
                ]);
                // Get handler for event. 
                var handler = this.get_events().getHandler(eventName);
                if (handler) {
                    if (!eventArgs) {
                        eventArgs = Sys.EventArgs.Empty;
                    }
                    // Fire event.                           
                    handler(this, eventArgs);
                }
            },
            _uriEncode: function(parameter) {
                if (encodeURIComponent) {
                    return encodeURIComponent(parameter);
                }
                else {
                    return escape(parameter);
                }
            },
            // This the handler for the Web request completed event
            _onCallbackCompleteHandler: function(executor, eventArgs) {
                var webRequest = executor.get_webRequest();
                var args, stringData, jsonData = null;
                if (executor.get_responseAvailable()) {
                    if (executor.get_statusCode() == '200') {
                        var response = executor.get_responseData();
                        if (response.charAt(0) == "s") {
                            stringData = response.substring(1);
                            jsonData = Sys.Serialization.JavaScriptSerializer.deserialize(stringData);
                            this.set_data(jsonData);
                            args = new Batik.Data.DataSourceEventArgs(this.get_data());
                            this._raiseEvent(webRequest.get_userContext() + 'Completed', args);
                        }
                        else if (response.charAt(0) == "e") {
                            //this.set_data(response.substring(1));
                            args = new Batik.Data.DataSourceEventArgs(null);
                            args.set_errorMessage(response.substring(1, response.length - 2));
                            this._raiseEvent(webRequest.get_userContext() + 'Error', args);
                        }
                        else {
                            var separatorIndex = response.indexOf("|");
                            if (separatorIndex != -1) {
                                var validationFieldLength = parseInt(response.substring(0, separatorIndex));
                                if (!isNaN(validationFieldLength)) {
                                    stringData = response.substring(separatorIndex + validationFieldLength + 1);
                                    jsonData = Sys.Serialization.JavaScriptSerializer.deserialize(stringData);
                                    this.set_data(jsonData);
                                    args = new Batik.Data.DataSourceEventArgs(this.get_data());
                                    this._raiseEvent(webRequest.get_userContext() + 'Completed', args);
                                }
                            }
                        }
                    }
                }
                else {
                    if (executor.get_timedOut())
                        alert("Timed Out");
                    else
                        if (executor.get_aborted())
                        alert("Aborted");
                }
            },

            _callback: function(callbackParam, commandName) {
                var webRequest = new Sys.Net.WebRequest();
                if (!theForm) {
                    var forms = document.getElementsByTagName('form');
                    if (forms.length > 0)
                        theForm = forms[0];
                }
                if (theForm.action)
                    webRequest.set_url(theForm.action);
                else {
                    return;
                }
                // Set the request verb.
                webRequest.set_httpVerb("POST");
                // Preparing request body
                var postData = '__EVENTTARGET=&__EVENTARGUMENT=' +
                "&__VIEWSTATE=" + this._uriEncode(theForm['__VIEWSTATE'].value) +
                "&__CALLBACKID=" + this.get_id() +
                "&__CALLBACKPARAM=" + this._uriEncode(Sys.Serialization.JavaScriptSerializer.serialize(callbackParam));
                if (theForm["__EVENTVALIDATION"]) {
                    postData += "&__EVENTVALIDATION=" + this._uriEncode(theForm["__EVENTVALIDATION"].value);
                }
                webRequest.set_body(postData);

                // Set the value of the HTTP header's "Content-Length".
                webRequest.get_headers()["Content-Length"] = postData.length;
                webRequest.get_headers()["Content-Type"] = "application/x-www-form-urlencoded; charset=utf-8";

                // Set the web request completed event handler,
                // for processing return data.
                webRequest.add_completed(Function.createDelegate(this, this._onCallbackCompleteHandler));

                webRequest.set_userContext(commandName);
                // Execute the request.
                webRequest.invoke();
            },
            selectData: function() {
                if (this.get_objectTypeName() && this.get_selectMethod()) {
                    var arg = { CommandName: 'Select', TypeName: this.get_objectTypeName(), CommandMethod: this.get_selectMethod() };
                    this._callback(arg, 'select');
                }
            },
            deleteData: function(dataItem) {
                if (this.get_objectTypeName() && this.get_deleteMethod()) {
                    var arg = { CommandName: 'Delete', TypeName: this.get_objectTypeName(), CommandMethod: this.get_deleteMethod(), Parameters: [dataItem] };
                    this._callback(arg, 'delete');
                }
            },
            updateData: function(dataItem) {
                if (this.get_objectTypeName() && this.get_updateMethod()) {
                    var arg = { CommandName: 'Update', TypeName: this.get_objectTypeName(), CommandMethod: this.get_updateMethod(), Parameters: [dataItem] };
                    this._callback(arg, 'update');
                }
            },
            insertData: function(dataItem) {
                if (this.get_objectTypeName() && this.get_insertMethod()) {
                    var arg = { CommandName: 'Insert', TypeName: this.get_objectTypeName(), CommandMethod: this.get_insertMethod(), Parameters: [dataItem] };
                    this._callback(arg, 'insert');
                }
            }
        }

        Batik.Data.ScriptDataSource.registerClass("Batik.Data.ScriptDataSource", Sys.Component);

        // create custom EventArgs class
        Batik.Data.DataSourceEventArgs = function(data) {
            Batik.Data.DataSourceEventArgs.initializeBase(this);
            this._data = data;
            this._errorMessage = null;
        };
        Batik.Data.DataSourceEventArgs.prototype = {
            get_data: function() {
                return this._data;
            },
            set_errorMessage: function(message) {
                this._errorMessage = message;
            },
            get_errorMessage: function() {
                return this._errorMessage;
            }
        }
        Batik.Data.DataSourceEventArgs.registerClass("Batik.Data.DataSourceEventArgs", Sys.EventArgs);
    }

    if (window.Sys && Sys.loader) {
        Sys.loader.registerScript("BatikScriptDataSource", null, execute);
    }
    else {
        execute();
    }

})();



